package com.jcsz.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.jcsz.common.to.es.SkuEsModel;
import com.jcsz.gulimall.search.config.GuliESConfig;
import com.jcsz.gulimall.search.constant.EsConstant;
import com.jcsz.gulimall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className: ProductSaveServiceImpl
 * @author: 一把Po吉他
 * @date: 2022/10/30 18:43
 * @version: 1.0
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();

        skuEsModels.forEach(item -> {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(item.getSkuId().toString());
            String jsonString = JSON.toJSONString(item);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        BulkResponse bulk = client.bulk(bulkRequest, GuliESConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        if (b) {
            List<String> collectIds = Arrays.asList(bulk.getItems()).stream().filter(obj -> obj.isFailed()).map(item -> item.getId()).collect(Collectors.toList());
            log.info("商品上架错误：{}", collectIds);
        }
        return !b;
    }
}
